package net.tavion.angelboot.gateway.security;

import net.tavion.angelboot.bsm.client.BsmClient;
import net.tavion.angelboot.bsm.dto.CustomerLoginReqDTO;
import net.tavion.angelboot.bsm.dto.CustomerLoginRspDTO;
import net.tavion.angelboot.common.utils.FrameworkUtils;
import net.tavion.angelboot.common.vo.GenericResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
public class SecurityUserDetailsService implements ReactiveUserDetailsService {

    @Resource
    BsmClient client;


    @Override
    public Mono<UserDetails> findByUsername(String username) {
//        RequestHeadDataHolder.initRequestData();
//        MDCUtil.putMDCKey(RequestHeadDataHolder.getRequestHeadData().getRequestId());

        CustomerLoginReqDTO loginReqDTO=new CustomerLoginReqDTO();
        loginReqDTO.setUsername(username);
        GenericResponse<CustomerLoginRspDTO> loginRsp= client.login(loginReqDTO);

        if(FrameworkUtils.notCallSuccess(loginRsp)){
            return Mono.error(new BadCredentialsException("login fail"));
        }

        CustomerLoginRspDTO customerLoginRspDTO=loginRsp.getData();
        if(null==customerLoginRspDTO){
            return Mono.error(new UsernameNotFoundException("User Not Found"));
        }

        UserDetails user = User.withUsername(username)
                .password("123455")
                .roles("admin").authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("admin"))
                .build();
        return Mono.just(user);

    }



}
